package com.ruoyi.common.mqtt;

import cn.hutool.extra.spring.SpringUtil;
import com.ruoyi.common.config.MqttConfig;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;

/**
 * @author Duke_yzl
 * @date 20230606.01
 * @describe：
 */
@Slf4j
public class OnMessageCallback implements MqttCallback {

    private YuMqttClient client;


    public OnMessageCallback(YuMqttClient yuMqttClient){
        this.client = yuMqttClient;
    }

    public void connectionLost(Throwable cause) {
        // 连接丢失后，一般在这里面进行重连
        if (client == null || !client.isConnected()) {
            log.info("连接断开，正在重连....");
            try {
                client.reconnect();
                MqttConfig bean = SpringUtil.getBean(MqttConfig.class);
                int[] qoss = new int[bean.getTopic().length];
                for (int i = 0; i < bean.getTopic().length; i++) {
                    qoss[i] = bean.getQos();
                }
                // 订阅
                client.subscribe(bean.getTopic(),qoss);
                log.info("mqtt重连完成.");
            } catch (MqttException e) {
                throw new RuntimeException(e);
            }
        }
    }

    public void messageArrived(String topic, MqttMessage message) throws Exception {
        // subscribe后得到的消息会执行到这里面
        System.out.println("接收消息主题:" + topic);
        System.out.println("接收消息Qos:" + message.getQos());
        System.out.println("接收消息内容:" + new String(message.getPayload()));
        String content = new String(message.getPayload());

    }

    public void deliveryComplete(IMqttDeliveryToken token) {
        System.out.println("deliveryComplete---------" + token.isComplete());
    }

}